<template>
    <div :class="'filebox '+className">
        <div class="file-input">
            <span v-html="title"></span>
            <input type="file" ref="file" :name="fileValue" :accept="accept" :multiple="number && number>1 ? true :false" @change="handleChange" :fileIds="fileIds">
        </div>
        <div class="file-info">
            <p>{{info}}</p>
        </div>
        <div class="file-list">
            <div class="file-item" v-for="(list,index) in lists">
                <div class="file-item-main" :title="list.originalFileName">
                    <img :src="list.fileType == 'IMAGE' || formateIsImg(list.fileFormat) ? baseurl + list.fileUrlDisplay : otherFileImg">
                    <span class="item-format">{{ list.fileFormat && list.fileFormat !=='' ? list.fileFormat.toUpperCase() : ''}}</span>
                    <div v-if="number>1" class="item-name">{{list.originalFileName}}</div>
                </div>
                <el-button v-if="number>1 ? true: false" type="text" @click="handleDelete(index)"><i class="el-icon-close"></i></el-button>
                <el-button v-if="isEdite" type="text" @click="handleEdite(index)" class="ct-file-edit-btn"><i class="el-icon-edit"></i></el-button>
            </div>
            <div class="file-item" v-for="(list,index) in newLists">
                <div class="file-item-main" :title="list.fileName">
                    <img :src="list.showImg">
                    <!--<div class="item-format">{{list.fileFormat}}</div>
                    <div class="item-name">{{list.fileName}}</div>-->
                </div>
                <el-button v-if="number>1 ? true: false" type="text" @click="handleDelete(index,'NEW')"><i class="el-icon-close"></i></el-button>
                <!--<el-button  type="text" @click="handleEdite(index,'NEW')" class="ct-file-edit-btn"><i class="el-icon-edit"></i></el-button>-->
            </div>
        </div>
    </div>
</template>
<script>
    // import { /*getFileList, deleteFile, uploadFileName*/} from '../../api/api'
    export default {
        name: 'upload-file',
        props: ['formate','title','number','accept','className','size','info','fileValue','fileIds','target','isEdite','singleFileInfo'],
        data () {
          return {
              multiple: true,
              files: [],
              lists: [],
              newLists: [],
              baseurl: '',
              otherFileImg: ''
          }
        },
        created (){
            if(this.fileIds && this.fileIds !=='') this.getFileItem ()
        },
        methods: {
            handleChange () {
                var file = this.$refs.file.files
                for(var i=0;i<file.length;i++) {
                    if(this.size && file[i].size > this.size*1024*1024){
                        this.$message.error('文件太大')
                        return false
                    }
                    if(this.number && this.number >1 && this.lists.length + this.newLists.length + 1 > this.number){
                        this.$message.error('最多只能添加'+this.number+'个文件')
                        return false
                    }
                    if(this.number == 1 ) this.files = [file[i]],this.lists = []
                    else this.files.push(file[i])
                    var li = file[i]
                        ,eli = {}
                        ,filename = li.name
                        ,format = filename.substring(filename.lastIndexOf(".")+1).toUpperCase()
                        ,name = filename.substring(0,filename.lastIndexOf("."))
                        ,type = li.type.indexOf('image/') > -1 ? 'IMAGE': 'OTHER'
                        ,showImg = this.otherFileImg
                    if(type == 'IMAGE'){
                        showImg = this.getObjectURL(li)
                    }
                    eli.fileFormat = format
                    eli.fileName = name
                    eli.fileType = type
                    eli.showImg = showImg
                    if(this.number == 1 ) this.newLists = [eli]
                    else this.newLists.push(eli)
                }
                this.$emit('handleChangeFile', this.returnFileInfo())
            },
            showFileList () {

            },
            handleDelete (index,status) {
                if(status && status == 'NEW'){
                    this.files = this.files.delete(index)
                    this.newLists = this.newLists.delete(index)
                    this.$emit('handleChangeFile', this.returnFileInfo())
                }else{
                    deleteFile(this.lists[index].id,this.target).then(res=>{
                        if(res.data.flag){
                            this.lists = this.lists.delete(index)
                            this.$emit('handleChangeFile', this.returnFileInfo())
                        }
                        else this.$message.error('服务端删除该文件失败')
                    }).catch( res=>{
                        this.$message.error('服务出错')
                    })
                }
            },
            getFileItem () {
                if(this.fileIds == '' || this.fileIds == undefined) return
                getFileList (this.fileIds,this.target).then( res=>{
                    if(res.data.success){
                        this.lists = res.data.result
                    }
                })
            },
            getObjectURL (file){
                var url=null
                if(window.createObjectURL!=undefined){
                    url=window.createObjectURL(file)
                }else if(window.URL!=undefined){
                    url=window.URL.createObjectURL(file)
                } else if(window.webkitURL!=undefined){
                    url=window.webkitURL.createObjectURL(file)
                }
                return url
            },
            formateIsImg (format) {
                var imgs = ['JPG','GIF','PNG','JPEG','BMP']
                    ,leng = imgs.length
                    ,format = format.toUpperCase()
                for(var i=0;i<leng;i++){
                    if(format == imgs[i]) return true
                }
            },
            handleEdite (index,type) {
                var isthis = this
                this.$prompt('修改文件名', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValue:type=='NEW'? this.newLists[index].fileName : this.lists[index].originalFileName ,
                    inputPattern: /^(?!\.)[^\\\/:\*\?"<>\|]{1,255}$/,
                    inputErrorMessage: '请输入正确的文件名'
                }).then(({ value }) => {
                    if(type && type=='NEW'){
                        var thisfile = isthis.files[index]
                            ,filename = thisfile.name
                            ,fileType = thisfile.type
                            ,format = filename.substring(filename.lastIndexOf(".")+1)
                            ,newFilename = value + '.'+format
                        isthis.files[index] = new File([thisfile], newFilename,{type:fileType})
                        isthis.newLists[index].fileName = value
                    }else{
                        uploadFileName(isthis.lists[index].id,isthis.target,value).then( res=>{
                            if(res.data.success){
                                isthis.lists[index].originalFileName = value
                                isthis.$message.success(res.data.msg)
                            }else{
                                isthis.$message.error(res.data.msg)
                            }
                        })
                    }
                }).catch(() => {

                });
            },
            returnFileInfo () {
                var json = {}
                json.file = this.files
                json.fileNum = this.newLists.length + this.lists.length
                json.fileValue = this.fileValue
                return json
            }
        },
        watch: {
            fileIds () {
                if(this.fileIds && this.fileIds !=='') this.getFileItem ()
            },
            singleFileInfo () {
                if(this.number == 1 && this.singleFileInfo && this.singleFileInfo !== ''){
                    var imgUrl = this.singleFileInfo
                        ,format = imgUrl.substring(imgUrl.lastIndexOf(".")+1).toUpperCase()
                        ,name = imgUrl.substring(0,imgUrl.lastIndexOf("."))
                    this.lists = [
                        {
                            originalFileName: name,
                            fileFormat: format,
                            fileUrlDisplay: imgUrl
                        }
                    ]
                }
            }

        }
    }
    Array.prototype.delete = function(delIndex){
        var temArray=[];
        for(var i=0;i<this.length;i++){
            if(i!=delIndex){
                temArray.push(this[i]);
            }
        }
        return temArray;
    }
</script>
<style scoped lang="stylus">
    .filebox{
        .file-input{
            width: 130px;
            height: 40px;
            position: relative;
            background-color: #00a1ed;
            border-radius: 2px;
            overflow: hidden;
            line-height: 40px;
            input{
                width: 100%;
                height: 100%;
                position: absolute;
                top:0;
                left: 0;
                opacity: 0;
            }
            span{
                width: 100%;
                height: 100%;
                display: block;
                text-align: center;
                line-height: inherit;
                font-size: 14px;
                color: #fff;
            }
        }
        .file-input:hover{
            background-color: #1977ed;
        }
        .file-info{
            color: #999999;
            font-size: 14px;
            line-height: 20px;
            padding: 5px 0;
        }
        .file-item{
            width: 100px;
            height: 100px;
            overflow: hidden;
            margin-right: 10px;
            margin-bottom: 10px;
            border-radius: 2px;
            box-shadow: 0 0 4px #999;
            float: left;
            position: relative;
            .file-item-main{
                width: 100%;
                height: 100%;
                position: relative;
            }
            img{
                max-width: 100%;
                max-height: 100%;
                transform: translate(-50%,-50%);
                position: absolute;
                top: 50%;
                left: 50%;
            }
            .item-name{
                line-height: 16px;
                background-color: rgba(0, 161, 237, 0.58);
                font-size: 12px;
                color: #fff;
                position: absolute;
                left: 0;
                bottom: 0;
                width: 100%;
                text-align: center;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
            .item-format{
                height: 30px;
                line-height: 30px;
                width: 100%;
                font-size: 18px;
                color: #fff;
                text-align: center;
                position: absolute;
                left: 0;
                top:50%;
                margin-top: -15px;
            }
            button{
                width: 16px;
                height: 16px;
                background-color: #666;
                border-radius: 0;
                position: absolute;
                top:0;
                right: 0;
                font-size: 16px;
                color: #c2c2c2;
                &:hover{
                     color: #fff;
                 }
                 i{
                     position: absolute;
                     top:1px;
                     left: 0px;
                 }
            }
            .ct-file-edit-btn{
                right:auto;
                left:0;
            }
        }
    }
</style>
